package com.darker.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLClientInfoException;
import java.sql.SQLIntegrityConstraintViolationException;

//全局异常处理类
//对以下注解的异常处理
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
    //处理增加员工 用户名重名的异常
    //java.sql.SQLIntegrityConstraintViolationException: Duplicate entry 'zhangsan' for key 'idx_username'
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        //判断是否属于这个异常
        if(ex.getMessage().contains("Duplicate")){
            //对这个字段进行分割出用户名 Duplicate entry 'zhangsan' for key 'idx_username'
            String[] s = ex.getMessage().split(" ");
            return R.error("用户名\t"+s[2]+"重名");
        }
        return R.error("未知错误");
    }
    //处理删除分类菜品的异常
    @ExceptionHandler(CustomException.class)
    public R<String> customException(CustomException ex){

        return R.error(ex.getMessage());
    }

}
